﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Model;
using KickStart.Data;

namespace KickStart.Helpers
{
    public static class MySession
    {
        private static readonly HttpRequest Request = HttpContext.Current.Request;
        private static readonly HttpSessionState session = HttpContext.Current.Session;
        private static readonly IIdentity identity = HttpContext.Current.User.Identity;

        public static string ConsumerKey
        {
            get
            {
                return ConfigurationManager.AppSettings["consumerKey"];

            }
        }

        public static string ConsumerSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["consumerSecret"];
            }
        }

        public static User CurrentUser
        {
            get
            {
                return session["CurrentUser"] as User;
            }
            set
            {
                session["CurrentUser"] = value;
            }
        }

        public static TwitterUser LoggedInTwitterUser
        {
            get
            {
                if (session["LoggedInTwitterUser"] == null && Request.IsAuthenticated)
                {
                    var twitterUser = User.SingleOrDefault(u => u.UserId == Convert.ToInt64(identity.Name));

                    if (twitterUser == null ||
                        string.IsNullOrEmpty(twitterUser.Token) ||
                        string.IsNullOrEmpty(twitterUser.TokenSecret))
                    {
                        FormsAuthentication.SignOut();
                        return null;
                    }

                    CurrentUser = twitterUser;

                    var twitter = FluentTwitter.CreateRequest()
                        .Configuration.UseGzipCompression()
                        .AuthenticateWith(ConsumerKey, ConsumerSecret, twitterUser.Token, twitterUser.TokenSecret)
                        .Users()
                        .ShowProfileFor(twitterUser.UserId)
                        .AsJson();

                    session["LoggedInTwitterUser"] = twitter.Request().AsUser();
                }
                return (TwitterUser)session["LoggedInTwitterUser"];
            }
            set
            {
                session["LoggedInTwitterUser"] = value;
                CurrentUser = UserService.GetUser(value.Id);
            }
        }

        public static string ReturnUrl
        {
            get { return session["ReturnUrl"] as string; }
            set { session["ReturnUrl"] = value; }

        }

    }
}
